using Identity.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Identity.Extensions
{
public class CustomUserClaimsPrincipalFactory(UserManager<User> userManager, IOptions<IdentityOptions> optionsAccessor) : UserClaimsPrincipalFactory< User>(userManager, optionsAccessor)
{
        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(User user)
{
    try
    {
 
        var identity = await base.GenerateClaimsAsync(user);
        if (!string.IsNullOrEmpty(user.DisplayName))
        {
                   
                    identity.AddClaim(new Claim("DisplayName", user.DisplayName));
             
        }

          if (!string.IsNullOrEmpty(user.Icon))
        {
              
     
                    identity.AddClaim(new Claim("Icon", user.Icon));
        }
        var roles = await UserManager.GetRolesAsync(user);
    
            foreach (var role in roles)
            {
                if (string.IsNullOrEmpty(role))
                {
        
                    continue;
                }

            
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }

        return identity;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"GenerateClaimsAsync 出现异常: {ex.Message}");
        throw;
    }
}
}
}